package com.sikadwafastdaisfondturbo.pretloan.ui.permission

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.sikadwa.lib_permission.XXPermissions
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.PermissionAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityPermissionBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.user.activity.UserLoginActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.TipsDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import org.json.JSONArray
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/16 14:26
 * @Annotation：权限列表
 */
class PermissionActivity: ProActivity() {
    private lateinit var binding: ActivityPermissionBinding

    //权限描述列表
    private var mItemAdapter: PermissionAdapter? = null
    //权限列表
    private val mPermissionList = arrayListOf<JSONObject>()
    //当前显示的权限
    var mPermissionIndex = 0

    override fun getRootView(): View {
        binding = ActivityPermissionBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        binding.parentLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        initRvPermission()
    }

    override fun initListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //联系客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Permission Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"Permission Page")
        }
        //上一个
        binding.imgLast.setOnClickListener {
            if (mPermissionIndex == 0){
                return@setOnClickListener
            }
            mPermissionIndex--
            showCurrentPermission()
            val item = mPermissionList[mPermissionIndex]
            addEvent(EventType.CLICK.CLICK_PERMISSION_LAST,item.optString("permission"))
        }
        //下一个
        binding.imgNext.setOnClickListener {
            if (mPermissionIndex == mPermissionList.size - 1){
                return@setOnClickListener
            }
            mPermissionIndex++
            showCurrentPermission()
            val item = mPermissionList[mPermissionIndex]
            addEvent(EventType.CLICK.CLICK_PERMISSION_NEXT,item.optString("permission"))
        }
        //拒绝权限
        binding.btnDeny.setOnClickListener {
            val item = mPermissionList[mPermissionIndex]
            item.put("isDeny",true)
            if (!item.optBoolean("isMust")){//非必须权限，需要设置为已点击状态
                item.put("isClick",true)
            }
            showBannedView()
            addEvent(EventType.CLICK.CLICK_PERMISSION_DENY,item.optString("permission"))
            mPermissionIndex = getPermissionIndex()
            showCurrentPermission()
        }
        //同意权限
        binding.btnAgree.setOnClickListener {
            val item = mPermissionList[mPermissionIndex]
            val confirmDialog = TipsDialog(this,item.optString("permission"),object : TipsDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    when(view!!.id){
                        R.id.btnOk -> {
                            hasRequestPermissions(item)
                            addEvent(EventType.CLICK.CLICK_PERMISSION_DIALOG_TIPS_OK,item.optString("permission"))
                        }
                        R.id.btnCancel -> {
                            addEvent(EventType.CLICK.CLICK_PERMISSION_DIALOG_TIPS_CANCEL,item.optString("permission"))
                        }
                    }
                }
            })
            confirmDialog.setCancelable(true)
            confirmDialog.setCanceledOnTouchOutside(false)
            confirmDialog.show()
            confirmDialog.setTipsTitle(resources.getString(R.string.tips_kind))
            confirmDialog.setTips(resources.getString(R.string.permission_agree_tips))

            addEvent(EventType.CLICK.CLICK_PERMISSION_AGREE,item.optString("permission"))
        }
        //已授权
        binding.btnAuthorized.setOnClickListener{
            val permission = mPermissionList[mPermissionIndex]
//            XXPermissions.startPermissionActivity(this,permission)
        }
        //被禁止
        binding.btnBanned.setOnClickListener {
            val item = mPermissionList[mPermissionIndex]
            XXPermissions.startPermissionActivity(this,item.optString("permission"))
            addEvent(EventType.CLICK.CLICK_PERMISSION_BANNED,item.optString("permission"))
        }
    }

    override fun initData() {
        mPermissionList.clear()
        val pDataArray = getPermissionArray()
        //手动添加一条
        pDataArray.put(getString(R.string.permission_app_list_title))
        for (i in 0..<pDataArray.length()){
            val permission = pDataArray.optString(i)
            mPermissionList.add(PermissionConfig.getPermissionItem(permission))
        }

//        mPermissionIndex = getPermissionIndex()
        //是否全部授权
        if (isAgreeAll()){
            onIntent(UserLoginActivity::class.java)
            finish()
            return
        }
        mPermissionIndex = getPermissionIndex()
        showCurrentPermission()
    }

    override fun onResume() {
        super.onResume()
//        isHasPermissions()
        mPermissionIndex = getPermissionIndex()
        showCurrentPermission()
    }

    /* 初始化列表 */
    private fun initRvPermission(){
//        binding.rvPermission.visibility = View.GONE
//        binding.rvPermission.setHasFixedSize(true)
//        binding.rvPermission.isNestedScrollingEnabled = false
//        binding.rvPermission.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(getContext())
        binding.rvPermission.layoutManager = layoutManager
        this.mItemAdapter = PermissionAdapter(binding.rvPermission)
        this.mItemAdapter!!.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mItemAdapter!!.getItem(position)
        }
        binding.rvPermission.adapter = this.mItemAdapter
    }

    /**
     * 获取权限列表
     */
    private fun getPermissionArray(): JSONArray{
        val bundle = intent.extras
        return JSONArray(bundle!!.getString("Permissings"))
    }

    /**
     * 显示权限信息
     */
    private fun showCurrentPermission(){
        if (mPermissionIndex == -1){
            return
        }
        val item = mPermissionList[mPermissionIndex]
        binding.imgIcon.setImageResource(item.optInt("icon"))
        binding.textTitle.text = item.optString("title")

        val msgArray = item.optJSONArray("msgList")
        val msgList = arrayListOf<JSONObject>()
        for (i in 0..<msgArray.length()){
            msgList.add(msgArray.optJSONObject(i))
        }
        mItemAdapter!!.data = msgList
        isHasPermissions()
    }

    /**
     * 是否申请了允许了当前权限
     */
    private fun isHasPermissions(){
        if (isAgreeAll()){
            onIntent(UserLoginActivity::class.java)
            finish()
            return
        }

        val item = mPermissionList[mPermissionIndex]
        //必须要申请的权限  APP LIST 只做展示
        if (item.optBoolean("isMust")){
            //是否已获得权限
            val isGranted = PermissionUtils.isAuthorized(this,item.optString("permission"))
            HHLog.e("${item.optString("permission")}>>>>>>>>是否已授权："+isGranted)
            //已获得权限
            if (isGranted){
                showAuthorizedView()
                return
            }
            //权限状态：0获取权限成功  1申请权限拒绝, 但是下次申请权限还会弹窗  2申请权限拒绝，并且是永久，不会再弹窗  3默认未请求授权状态
            val authorizeStaus = PermissionUtils.getAuthorizeStaus(this,item.optString("permission"))
            HHLog.e("${item.optString("permission")}>>>>>>>>状态：$authorizeStaus")
            //2申请权限拒绝，并且是永久，不会再弹窗 || 本次已拒绝
            if (authorizeStaus == 2 || item.optBoolean("isDeny",false)){
                showBannedView()
                return
            }
            showDefaultView()
        } else {//非必须要申请的权限，根据isDeny 或 isAgree 显示状态
            if (item.optBoolean("isDeny")){
                showBannedView()
                return
            }
            if (item.optBoolean("isAgree")){
                showAuthorizedView()
                return
            }
            showDefaultView()
        }
    }

    /**
     * 申请权限
     */
    fun hasRequestPermissions(item: JSONObject){
        //非必须申请的权限
        if (!item.optBoolean("isMust")){
            item.put("isAgree",true)
            item.put("isClick",true)
            showAuthorizedView()
            //验证是否全部已同意
            if (isAgreeAll()){
                onIntent(UserLoginActivity::class.java)
                finish()
            } else {
                //最后一个
                if (mPermissionIndex == mPermissionList.size - 1){
                    mPermissionIndex = getPermissionIndex()
                } else {
                    mPermissionIndex++
                }
                showCurrentPermission()
            }
            return
        }
        val permission = item.optString("permission")
        PermissionUtils.requestPermission(this,permission,object : PermissionListener{
            override fun requestResult(isFlog: Boolean) {
                HHLog.e("requestResult>>>>>>>>>>>>>>$isFlog")
                if (isFlog){
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permission)
                    showAuthorizedView()
                    //验证是否全部已同意
                    if (isAgreeAll()){
                        onIntent(UserLoginActivity::class.java)
                        finish()
                        return
                    }
                } else {
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,permission)
                    showBannedView()
                    //最后一个
//                    if (mPermissionIndex == mPermissionList.size - 1){
//                        mPermissionIndex = getPermissionIndex()
//                    } else {
//                        mPermissionIndex++
//                    }
                }
                mPermissionIndex = getPermissionIndex()
                showCurrentPermission()
            }
        })
    }

    /* 权限请求监听 */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtils.onRequestPermissionsResult(this,requestCode, permissions,grantResults)
    }

    /**
     * 未申请
     */
    private fun showDefaultView(){
        val item = mPermissionList[mPermissionIndex]
        HHLog.e("${item.optString("permission")}——————> 权限未申请")
        binding.normalLayout.visibility = View.VISIBLE
        binding.btnAuthorized.visibility = View.GONE
        binding.btnBanned.visibility = View.GONE
    }

    /**
     * 已允许
     */
    private fun showAuthorizedView(){
        val item = mPermissionList[mPermissionIndex]
        HHLog.e("${item.optString("permission")}——————> 权限已允许")
        binding.normalLayout.visibility = View.GONE
        binding.btnAuthorized.visibility = View.VISIBLE
        binding.btnBanned.visibility = View.GONE
    }

    /**
     * 已拒绝
     */
    private fun showBannedView(){
        val item = mPermissionList[mPermissionIndex]
        HHLog.e("${item.optString("permission")}——————> 权限已拒绝")
        binding.normalLayout.visibility = View.GONE
        binding.btnAuthorized.visibility = View.GONE
        binding.btnBanned.visibility = View.VISIBLE
    }

    /**
     * 获取未授权的权限下标
     */
    private fun getPermissionIndex(): Int{
        var index = mPermissionIndex
        if (mPermissionList.size > 0){
            for (i in 0..<mPermissionList.size){
                val item = mPermissionList[i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(this,item.optString("permission")) && !item.optBoolean("isDeny",false)){
                        index = i
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick")){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 是否全部已授权
     */
    private fun isAgreeAll(): Boolean{
        var isAll = true
        if (mPermissionList.size > 0){
            for (i in 0..<mPermissionList.size){
                val item = mPermissionList[i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(this,item.optString("permission"))){
                        isAll = false
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick")){
                        isAll = false
                        break
                    }
                }
            }
        }
        return isAll
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_PERMISSION_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_PERMISSION_END,"")
    }
}